package body MIDI.Control_Events is


   function To_Pitch_Value (P : Pitch_Wheel_Change_Event) return Uint16_be
   is
      Mask : constant := 16#7F#;
   begin
      return Uint16_be(P.LSB and Mask) + Uint16_be(P.MSB and Mask) * 128;
   end To_Pitch_Value;

   procedure Read (
      From : not null access Root_Stream_Type'Class;
      C    : out Control_Event 
      )
   is
   begin
      case C.Name is
         when Note_Off            => Note_Off_Event'Read(From,            C.As_Note_Off);
         when Note_On             => Note_On_Event'Read(From,             C.As_Note_On);
         when Key_After_Touch     => Key_After_Touch_Event'Read(From,     C.As_Key_After_Touch);
         when Controller_Change   => Controller_Change_Event'Read(From,   C.As_Controller_Change);
         when Program_Change      => Program_Change_Event'Read(From,      C.As_Program_Change);
         when Channel_After_Touch => Channel_After_Touch_Event'Read(From, C.As_Channel_After_Touch);
         when Pitch_Wheel_Change  => Pitch_Wheel_Change_Event'Read(From,  C.As_Pitch_Wheel_Change);
      end case;
   end Read;

   procedure Write (
      From : not null access Root_Stream_Type'Class;
      C    : Control_Event 
      )
   is
   begin
      case C.Name is
         when Note_Off            => Note_Off_Event'Write(From,            C.As_Note_Off);
         when Note_On             => Note_On_Event'Write(From,             C.As_Note_On);
         when Key_After_Touch     => Key_After_Touch_Event'Write(From,     C.As_Key_After_Touch);
         when Controller_Change   => Controller_Change_Event'Write(From,   C.As_Controller_Change);
         when Program_Change      => Program_Change_Event'Write(From,      C.As_Program_Change);
         when Channel_After_Touch => Channel_After_Touch_Event'Write(From, C.As_Channel_After_Touch);
         when Pitch_Wheel_Change  => Pitch_Wheel_Change_Event'Write(From,  C.As_Pitch_Wheel_Change);
      end case;
   end Write;

end MIDI.Control_Events;
